import React from 'react'
import { connect } from 'dva'
import { Link } from 'dva/router'
import Header from '../../../components/Header/index'
import { Input, Checkbox, Button, Row, Col, Skeleton, Form, message } from 'antd'
import styles from './EditRole.less'
import PropTypes from 'prop-types'
import gql from 'graphql-tag'
import { GQL as AGQL } from '../../../components/GQL/index'

const SaveButton = ({ editPermissionGroups, validateFields, ruleGroupIds, groupId }) => {
  const save = () => {
    validateFields((err, data) => {
      if (!err) {
        let { groupName } = data
        editPermissionGroups({
          variables: { group: { groupName, ruleGroupIds: ruleGroupIds(), groupId } }
        }).then(({ data: { editPermissionGroups } }) => {
          const { status } = editPermissionGroups
          if (status === 'fail') {
            message.error(editPermissionGroups.message)
            return
          }
          message.success(editPermissionGroups.message)
        })
      }
    })
  }
  return (
    <Button type='primary' onClick={() => save()}>确认</Button>
  )
}
SaveButton.propTypes = {
  editPermissionGroups: PropTypes.func,
  groupName: PropTypes.string,
  ruleGroupIds: PropTypes.func,
  validateFields: PropTypes.func,
  groupId: PropTypes.number
}

const SaveButtonAGQL = AGQL({
  mutation: gql`
    mutation editPermissionGroups($group: GroupInput!){
      editPermissionGroups(group: $group) {
        status
        message
      }
    }
  `,
  name: 'editPermissionGroups'
})(SaveButton)

function EditRole ({ loading, data, updateQuery, rolePermission, form: { getFieldDecorator, validateFields } }) {
  let { role = {} } = rolePermission
  const headerData = {
    title: role.groupId ? '编辑权限组' : '新增角色',
    hasSubNav: true,
    subNavItem: [
      {
        title: '首页',
        link: true
      },
      {
        title: '基础设置',
        link: false
      },
      {
        title: '账号管理',
        link: false
      },
      {
        title: '角色权限',
        link: true
      }
    ]
  }

  const { accountGroupInfo = {} } = data
  const { permissions = [], groupName, groupId } = accountGroupInfo
  const changeSelectStatus = (index) => {
    updateQuery((previousResult, { variables }) => {
      let { accountGroupInfo: { permissions = [] } } = previousResult
      permissions[index].status = !permissions[index].status
      permissions[index].children.forEach(item => { item.status = permissions[index].status })
      return previousResult
    })
  }

  const changeSelectList = (index, _index) => {
    updateQuery((previousResult, { variables }) => {
      let { accountGroupInfo: { permissions = [] } } = previousResult
      permissions[index].children[_index].status = !permissions[index].children[_index].status
      permissions[index].status = !permissions[index].children.every(item => item.status === false)
      return previousResult
    })
  }

  const getCheckedIds = () => {
    let ids = []
    permissions.map((t, k) => {
      if (t.status) { ids = [...ids, t.ruleGroupId] }
      if (t.children) {
        t.children.map(_t => {
          if (_t.status) { ids = [...ids, _t.ruleGroupId] }
        })
      }
    })
    return ids
  }

  return (
    <div>
      <div>
        <Header header={headerData} />
      </div>
      <div className={styles.addName}>
        <span>角色名称</span>
        {
          getFieldDecorator('groupName', { initialValue: groupName || '' })(
            <Input className={styles.inp} style={{ width: 300 }} />
          )
        }

      </div>
      <div className={styles.checkboxlist}>
        <span style={{ position: 'absolute' }}>权限明细</span>
        <div className={styles.wrapper}>
          <Skeleton active loading={loading}>
            {
              permissions.map((item, index) => {
                return (
                  <div style={{ borderBottom: '1px solid #ccc', padding: '20px 0px' }} key={`permission-check-group-${index}`}>
                    <Row>
                      <Col span={2}>
                        <Checkbox onChange={() => changeSelectStatus(index)} checked={item.status === true} className={styles.dingdan}>{item.ruleGroupName}</Checkbox>
                      </Col>
                      <Col span={22}>
                        <Row>
                          {
                            item.children && item.children.map((_item, _index) => <Col span={8} key={`permisession-check-${index}-${_index}`}>
                              <Checkbox onChange={() => changeSelectList(index, _index)} checked={_item.status === true}>
                                {_item.ruleGroupName}
                              </Checkbox>
                            </Col>)
                          }
                        </Row>
                      </Col>
                    </Row>
                  </div>
                )
              })
            }
          </Skeleton>
        </div>
      </div>
      <div className={styles.footer}>
        <SaveButtonAGQL groupId={groupId} ruleGroupIds={() => getCheckedIds()} validateFields={validateFields} />
        <Link to='/RolePermission'><Button>取消</Button></Link>
      </div>
    </div>
  )
}

EditRole.propTypes = {
  loading: PropTypes.bool,
  data: PropTypes.object,
  updateQuery: PropTypes.func,
  form: PropTypes.object,
  rolePermission: PropTypes.object
}

const mapStateToProps = ({ rolePermission }) => ({ rolePermission })

const EditRoleAQL = ({ variables }) => {
  const Component = AGQL({
    query: gql`
      query accountGroupInfo($groupId: Int){
        accountGroupInfo(groupId: $groupId) {
          groupId
          groupName
          groupRemark
          ruleGroupIds
          permissions {
            ruleGroupId
            ruleGroupName
            status
            children {
              ruleGroupId
              ruleGroupName
              status
            }
          }
        }
      }
    `,
    variables
  })(connect(mapStateToProps)(Form.create()(EditRole)))

  return <Component />
}

EditRoleAQL.propTypes = {
  variables: PropTypes.object
}

const EditRoleView = ({ history, location }) => {
  const search = history.location.search
  const reg = /\?groupId=(\d+)?/g
  const res = reg.exec(search)
  let groupId = 0
  if (res) {
    groupId = parseInt(res[1])
  }

  return (
    <div>
      <EditRoleAQL variables={{ groupId }} />
    </div>
  )
}

EditRoleView.propTypes = {
  history: PropTypes.object,
  location: PropTypes.object
}

export default EditRoleView
